package com.restaurant.springboot.controller;

import com.restaurant.springboot.annotation.TokenAuth;
import com.restaurant.springboot.entity.CouponEntity;
import com.restaurant.springboot.entity.UserEntity;
import com.restaurant.springboot.entity.dto.CouponDTO;
import com.restaurant.springboot.service.CouponSeriseService;
import com.restaurant.springboot.service.CouponService;
import com.restaurant.springboot.utils.RespCode;
import com.restaurant.springboot.utils.RespEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.sql.Timestamp;

@RestController
@RequestMapping("api/coupon")
public class CouponController {

    @Autowired
    private CouponService couponService;

    @Autowired
    private CouponSeriseService couponSeriseService;

    @GetMapping("")
    @TokenAuth
    public RespEntity getAllCouponByUserId(HttpSession httpSession){
        UserEntity user = (UserEntity) httpSession.getAttribute("user");
        if(user == null){
            return new RespEntity(
                    RespCode.NO_LOGIN
            );
        }
        int userId = user.getId();
        return new RespEntity(RespCode.SUCCESS,couponService.getAllCouponByUserId(userId));
    }

    @PostMapping("")
    @TokenAuth
    public RespEntity takeCoupon(@RequestBody CouponDTO couponDTO,HttpSession session){
        UserEntity user = (UserEntity) session.getAttribute("user");
        if(user==null){
            return new RespEntity(RespCode.ERROR,"user is not exists",null);
        }
        if(couponSeriseService.getCouponSeriesById(couponDTO.getCouponSeriesId())!=null){
            CouponEntity coupon = couponService.getCoupon(user.getId(),couponDTO.getCouponSeriesId());
            if(coupon==null){
                Timestamp time = new Timestamp(System.currentTimeMillis());
                if(couponService.takeCoupon(user.getId(),couponDTO.getCouponSeriesId(),time)){
                    return new RespEntity(RespCode.SUCCESS,"take coupon success",null);
                }else{
                    return new RespEntity(RespCode.ERROR,"take coupon fail",null);
                }
            }else if(coupon!=null&&!coupon.isUsed()){
                return new RespEntity(RespCode.ERROR,"coupon is taken",null);
            }else if(coupon!=null&&coupon.isUsed()){
                coupon.setUsed(false);
                if(couponService.updateCoupon(coupon)){
                    return new RespEntity(RespCode.SUCCESS,"take coupon success",null);
                }else{
                    return new RespEntity(RespCode.ERROR,"take coupon fail",null);
                }
            }
        }
        return new RespEntity(RespCode.ERROR,"coupon series is not exists",null);
    }

}
